package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {

    // 数据库的约束错误信息，可能有很多：主键 唯一 非空约束 外键约束
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerSQLConstraintException(SQLIntegrityConstraintViolationException exception) {
        // 1、打印异常信息 log.error()  getMessage
        log.error(exception.getMessage());
        // 2、获取异常信息 getMessage()  Duplicate entry '111' for key 'idx_username'
        if (exception.getMessage().contains("Duplicate entry")) {
            String[] msgs = exception.getMessage().split(" ");
            String msg = msgs[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");

    }
    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(CustomException exception) {
        // 1、打印异常信息 log.error()  getMessage
        log.error(exception.getMessage());

        return R.error(exception.getMessage());

    }
}
